#include "tcp_socket_server.h"
#include <QDebug>

namespace infrastructure {
namespace io {

TcpSocketServer::TcpSocketServer(int numConnections, QObject *parent)
    : QTcpServer(parent)
    , maxConnections(numConnections)
    , nConnectCount(0)
{
    setMaxPendingConnections(numConnections);
}

TcpSocketServer::~TcpSocketServer()
{
    emit this->sentDisConnect(-1);
    this->close();
}

void TcpSocketServer::setMaxPendingConnections(int numConnections)
{
    this->QTcpServer::setMaxPendingConnections(numConnections);
    this->maxConnections = numConnections;
}

void TcpSocketServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug() << "新连接 socketDescriptor=" << socketDescriptor;

    // 检查是否超过最大连接数
    if (tcpClient.size() >= maxConnections) {
        QTcpSocket tcp;
        tcp.setSocketDescriptor(socketDescriptor);
        tcp.disconnectFromHost();
        qDebug() << "拒绝连接: 已达到最大连接数";
        return;
    }

    // 创建新的TCP客户端
    TcpSocketClient* tcpTemp = new TcpSocketClient(socketDescriptor);
    QString ip = tcpTemp->peerAddress().toString();
    quint16 port = tcpTemp->peerPort();

    // 连接信号
    connect(tcpTemp, &TcpSocketClient::sig_sockDisConnect, this, &TcpSocketServer::sockDisConnectSlot);
    connect(this, &TcpSocketServer::sentDisConnect, tcpTemp, &TcpSocketClient::disConTcp);

    // 插入到连接管理中
    tcpClient.insert(socketDescriptor, tcpTemp);
    emit sig_connectClient(socketDescriptor, ip, port);

    nConnectCount++;
    qDebug() << "当前连接个数为:" << nConnectCount;
}

void TcpSocketServer::sockDisConnectSlot(qint64 socketDescriptor, const QString& ip, quint16 port, QThread* th)
{
    Q_UNUSED(th);

    nConnectCount--;
    qDebug() << "断开连接 socketDescriptor=" << socketDescriptor;
    qDebug() << "当前连接个数为:" << nConnectCount;

    // 从连接管理中移除
    tcpClient.remove(socketDescriptor);
    emit sig_sockDisConnect(socketDescriptor, ip, port);
}

void TcpSocketServer::clear()
{
    emit this->sentDisConnect(-1);
    tcpClient.clear();
    nConnectCount = 0;
}

} // namespace io
} // namespace infrastructure
